<template>
  <div class="system-user">
    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入姓名" 
            clearable 
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roleId" placeholder="请选择" clearable>
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建用户
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="姓名" width="100" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="roleName" label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" size="small">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="最后登录" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleResetPassword(row)">
              重置密码
            </el-button>
            <el-button type="text" size="small" @click="handleAssignRole(row)">
              分配角色
            </el-button>
            <el-popconfirm title="确定删除该用户吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建用户' : '编辑用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" :disabled="dialogType === 'edit'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="formData.realName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="dialogType === 'create'">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="formData.confirmPassword" type="password" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="formData.roleIds" multiple placeholder="请选择角色">
            <el-option 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { getUsers, createUser, updateUser, deleteUser, getUserDetail, getRoles } from '@/api/admin'

export default {
  name: 'SystemUser',
  components: {
    Search, Refresh, Plus, Delete
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('create')
    const selectedRows = ref([])
    const formRef = ref()

    const searchForm = reactive({
      username: '',
      realName: '',
      roleId: '',
      status: ''
    })

    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })

    const tableData = ref([])
    const roleList = ref([])

    const formData = reactive({
      id: '',
      username: '',
      realName: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
      roleIds: [],
      status: 1,
      remark: ''
    })

    const formRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== formData.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      roleIds: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    // 加载表格数据
    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getUsers({
          page: pagination.current - 1,
          size: pagination.size,
          ...searchForm
        })
        
        if (res.data) {
          tableData.value = res.data.content || []
          pagination.total = res.data.totalElements || 0
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }

    // 加载角色列表
    const loadRoleList = async () => {
      try {
        const res = await getRoles()
        if (res.data) {
          roleList.value = res.data.content || []
        }
      } catch (error) {
        console.error('加载角色列表失败:', error)
        ElMessage.error('加载角色列表失败')
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        username: '',
        realName: '',
        roleId: '',
        status: ''
      })
      handleSearch()
    }

    // 新建
    const handleCreate = () => {
      dialogType.value = 'create'
      dialogVisible.value = true
      resetFormData()
    }

    // 编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      Object.assign(formData, {
        ...row,
        roleIds: row.roles.map(r => r.id)
      })
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteUser(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 批量删除
    const handleBatchDelete = async () => {
      if (!selectedRows.value.length) return
      
      try {
        await ElMessageBox.confirm('确定删除选中的用户吗？', '提示', {
          type: 'warning'
        })
        
        const ids = selectedRows.value.map(row => row.id)
        const res = await deleteUser(ids)
        if (res.code === 200) {
          ElMessage.success('批量删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 状态变更
    const handleStatusChange = async (row) => {
      try {
        const res = await updateUser(row.id, { status: row.status })
        if (res.code === 200) {
          ElMessage.success(`${row.status ? '启用' : '禁用'}成功`)
        }
      } catch (error) {
        row.status = !row.status
        ElMessage.error('操作失败')
      }
    }

    // 重置密码
    const handleResetPassword = async (row) => {
      try {
        await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await updateUser(row.id, { resetPassword: true })
        if (res.code === 200) {
          ElMessage.success('密码已重置为：123456')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('重置密码失败')
        }
      }
    }

    // 分配角色
    const handleAssignRole = async (row) => {
      // 实现角色分配逻辑
      ElMessage.info('角色分配功能开发中')
    }

    // 选择变更
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let res
        if (dialogType.value === 'create') {
          res = await createUser(formData)
        } else {
          res = await updateUser(formData.id, formData)
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        username: '',
        realName: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        roleIds: [],
        status: 1,
        remark: ''
      })
    }

    onMounted(() => {
      loadTableData()
      loadRoleList()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogType,
      selectedRows,
      formRef,
      searchForm,
      pagination,
      tableData,
      roleList,
      formData,
      formRules,
      loadTableData,
      handleSearch,
      handleReset,
      handleCreate,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleStatusChange,
      handleResetPassword,
      handleAssignRole,
      handleSelectionChange,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.system-user {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 